//
//  LXComposeViewController.m
//  微了个小博
//
//  Created by imera on 15/11/24.
//  Copyright (c) 2015年 imera. All rights reserved.
//

#import "LXComposeViewController.h"
#import "AFNetworking.h"
#import "LXAcount.h"
#import "MBProgressHUD+MJ.h"
#import "LXTextView.h"

@interface LXComposeViewController ()
@property (nonatomic, weak) LXTextView *textView;

@end

@implementation LXComposeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //设置导航栏按钮样式
    [self setupBarButtonStyle];
    
    //初始化输入控件
    [self setupTextview];
}

/**
 *  设置导航栏按钮样式
 */
- (void)setupBarButtonStyle
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"发微博";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStyleDone target:self action:@selector(send)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

/**
 *  初始化输入控件
 */
- (void)setupTextview
{
    //创建textview
    LXTextView *textView = [[LXTextView alloc]init];
    textView.frame = self.view.bounds;
    textView.font = LXComposeFont;
    textView.placeHolder = @"分享新鲜事";
    self.textView = textView;
    [self.view addSubview:textView];
    
    //监听textview改变的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:textView];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];   
}

- (void)textChange
{
    self.navigationItem.rightBarButtonItem.enabled = self.textView.text.length;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.textView becomeFirstResponder];
}

- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)send
{
    // 1.创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    // 2.封装请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = [LXAcount Acount].access_token;
    params[@"status"] = self.textView.text;
    
    // 3.发送请求
    [mgr POST:@"https://api.weibo.com/2/statuses/update.json" parameters:params
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
          [MBProgressHUD showSuccess:@"发表成功"];
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          [MBProgressHUD showSuccess:@"发表失败"];
      }];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
